import React, { useState, useEffect } from 'react';

import './search.less'

import { Input, Space, Tag, message  } from 'antd';
const { Search } = Input;
import { nanoid } from "nanoid"
export default function(props){
    const [arr, setArr] = useState([])
    const [value, setValue] = useState('')
  const onSearch = value =>{  //  回车搜索按钮
    let a = JSON.parse(JSON.stringify(arr))
    if(arr.length === 500) {
        message.warning('只能输入500项');
        return
    }
    if(value) {
        let itemObj = {id: nanoid(), name: value}
        a.push(itemObj)
        setArr(a)
        props.onSearch && props.onSearch(a)
       setValue('')
    }
    
  }

  useEffect(() => {
    if(props.value) {
      let a = props.value
      let b = a.map(m => ({id: nanoid(), name: m}))
      setArr(b)
    }
  }, [] )


 
  const onChange = (e) => {
    setValue(e.target.value)
  }
  const log = (e, item, index) => {
    let a = JSON.parse(JSON.stringify(arr))
    let b = a.filter(f => {
        return f.id !== item.id
    })
    setArr(b)
  }



  return (
    <div style={{padding: '20px'}} >
        <Search
            placeholder="关键词, 以逗号分割"
            allowClear
            enterButton="增加"
            onSearch={onSearch}
            value={value}
            onChange={onChange}
            style={{
                width: '300px'
            }}
        />
        <div style={{margin: '10px 0'}} > 已经输入{arr.length}项, 还可以输入{500-arr.length}项 </div>
        { arr.length>0 && (
            <div style={{ display: 'flex' }} className="tag" >
                {arr.map((item, index) => {
                    return ( <div key={item.id} style={{margin: '5px 6px'}} >
                       <Tag closable  onClose={(e)=> log(e, item, index)} style={{color: '#fff', background:"#56b6ee"}} >  {item.name} </Tag>
                    </div> )
                })}
            </div>
        ) }

    </div>
  )
}